package com.xzz.treeBST;

/**
 * @author: hhz
 * @create: 2021-12-20 15:56
 * 538. 把二叉搜索树转换为累加树
 * 给出二叉 搜索 树的根节点，该树的节点值各不相同，请你将其转换为累加树（Greater Sum Tree），使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
 *
 * 提醒一下，二叉搜索树满足下列约束条件：
 *
 * 节点的左子树仅包含键 小于 节点键的节点。
 * 节点的右子树仅包含键 大于 节点键的节点。
 * 左右子树也必须是二叉搜索树。
 *
 **/
public class ConvertBST {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(4);
        TreeNode node2 = new TreeNode(1);
        TreeNode node3 = new TreeNode(6);
        TreeNode node4 = new TreeNode(0);
        TreeNode node5 = new TreeNode(2);
        TreeNode node6 = new TreeNode(5);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(3);
        TreeNode node9 = new TreeNode(8);

        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node5.right = node8;
        node7.right = node9;
        print(node1);
        convertBST(node1);
        System.out.println();
        print(node1);

        
    }
    static Integer sum = 0;
    public static TreeNode convertBST(TreeNode root) {
        sum = 0;
        greaterBST(root);
        return root;
    }

    public static void greaterBST(TreeNode root) {
        if(root == null){
            return;
        }
        //先右后左，BST逆序
        greaterBST(root.right);

        sum = sum + root.val;
        root.val = sum;

        greaterBST(root.left);
    }

    public static void print(TreeNode root){
        if(null==root){
            System.out.print("null,");
            return;
        }
        System.out.print(root.val+",");
        print(root.left);
        print(root.right);
    }
}
